package com.seocoo.worker.base.version;

import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.google.gson.Gson;
import com.seocoo.worker.R;
import com.seocoo.worker.base.entity.EVersion;
import com.sfh.lib.AppCacheManager;
import com.sfh.lib.http.down.HttpDownHelper;
import com.sfh.lib.http.down.ProgressListener;

import java.io.File;

import static com.sfh.lib.AppCacheManager.getCacheListener;

/**
 * 功能描述:APK后台下载服务
 */
public class APKLoadService extends IntentService {

    public static void startLoadService(Context context, EVersion version) {

        Intent intent = new Intent(context, APKLoadService.class);
        intent.putExtra("DATA", new Gson().toJson(version));
        context.startService(intent);
    }

    private static final String VERSION_CODE = "version_code";
    public static final String ACTION = "com.door.apk";
    private File mApk;
    private NotificationManager notificationManager;
    private EVersion version;
    private static final int NOTIFI_ID = 0x127;
    private NotificationCompat.Builder progressNotificationBuilder;

    public APKLoadService() {
        super("APKLoadService");
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        this.notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        this.version = new Gson().fromJson(intent.getStringExtra("DATA"), EVersion.class);
        if (this.loadAPK(version)) {
            this.createNotification("正在下载", 0);
            try {
                final long m = 1024 * 1024;
                new HttpDownHelper.Builder(version.linkUrl + "?currentTime=" + System.currentTimeMillis())
                        .setTagFile(mApk).setProgressListener(new ProgressListener() {
                    @Override
                    public void onProgress(long total, long percent, long progress) {
                        // 发送内部广播 回调
                        Intent data = new Intent(ACTION);
                        data.putExtra("type", "LOAD");
                        data.putExtra("size", percent);
                        data.putExtra("loadSize", (float) progress / m);
                        data.putExtra("allSize", (float) total / m);
                        LocalBroadcastManager.getInstance(APKLoadService.this).sendBroadcast(data);

                        String txt = "正在下载 " + String.format("%.2f M/%.2f M", ((float) progress / m), ((float) total / m));
                        createNotification(txt, (int) percent);
                    }
                }).start();

            } catch (Exception e) {
                Intent data = new Intent(ACTION);
                data.putExtra("type", "ERROR");
                LocalBroadcastManager.getInstance(this).sendBroadcast(data);
            }
        }

        this.notificationManager.cancel(NOTIFI_ID);

        if (ApkCheckUtils.isLegalApk(mApk.getAbsolutePath())) {

            //检查APK 完整性,安装
            Intent data = new Intent(ACTION);
            data.putExtra("type", "LOAD");
            data.putExtra("size", 101L);
            data.putExtra("apk", mApk.getAbsolutePath());
            LocalBroadcastManager.getInstance(this).sendBroadcast(data);
            ApkCheckUtils.installApk(this, mApk, "com.seocoo.worker.base.WorkerFileProvider");

        } else {
            // 更新子线程中回调
            Intent data = new Intent(ACTION);
            data.putExtra("type", "ERROR");
            LocalBroadcastManager.getInstance(this).sendBroadcast(data);
            Toast.makeText(this, "下载更新失败", Toast.LENGTH_LONG).show();
        }
    }

    private void createNotification(String msg, int size) {

        if (progressNotificationBuilder == null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                NotificationChannel channel = new NotificationChannel("DEFAULT_CHANNEL_ID", "DEFAULT_CHANNEL_NAME", NotificationManager.IMPORTANCE_HIGH);
                NotificationManager mNotificationManager = getSystemService(NotificationManager.class);
                mNotificationManager.createNotificationChannel(channel);

                progressNotificationBuilder = new NotificationCompat.Builder(this, "DEFAULT_CHANNEL_ID");
            } else {
                progressNotificationBuilder = new NotificationCompat.Builder(this);
            }
            progressNotificationBuilder.setSmallIcon(R.drawable.ic_launcher);
        }
        progressNotificationBuilder.setContentTitle(msg);
        progressNotificationBuilder.setProgress(100, size, false);
        notificationManager.notify(NOTIFI_ID, progressNotificationBuilder.build());
    }

    /**
     * ---------------------------------------- 本地File start-------------------------------------------------------
     */
    private boolean loadAPK(final EVersion data) {

        // 1 检查APK 文件是否存在
        String fileName = "易窗-工匠端" + data.version;
        mApk = exitFile(fileName);
        if (!mApk.exists() || mApk.length() <= 0) {
            //文件不存在 or 未下载，网络下载
            return true;
        }
        // 2 检查APK文件完整性
        if (ApkCheckUtils.isLegalApk(mApk.getAbsolutePath())) {

            //已经下载完成
            return false;
        } else {
            //网络下载
            return true;
        }
    }

    /***
     * 文件是否存在
     */
    private File exitFile(String name) {

        String fileName;
        File updateDir = new File(AppCacheManager.getFileCache(), "apk");
        // 创建目录
        if (!updateDir.exists()) {
            updateDir.mkdirs();
        }

        //每次更新版本不一致时，删除更新目录下的所以文件，下载保存数据
        clearLoadFile(updateDir, name);
        fileName = updateDir + File.separator + name + ".apk";

        return new File(fileName);
    }

    /***
     * 删除更新目录下的所以文件qing
     * @param pathFile
     * @param name
     */
    private void clearLoadFile(File pathFile, String name) {

        if (!pathFile.exists()) {
            return;
        }
        //每次更新版本不一致时，删除更新目录下的所以文件qing
        String versionCode = getCacheListener().getString(VERSION_CODE, "");
        if (!TextUtils.equals(name, versionCode)) {
            AppCacheManager.getPersistListener().putString(VERSION_CODE, name, true);
            this.deleteAllFiles(pathFile);
        }
    }


    private void deleteAllFiles(File root) {

        File[] files = root.listFiles();
        if (files == null || files.length <= 0) {
            return;
        }
        for (File f : files) {
            if (f.isFile()) {
                f.delete();

            } else if (f.isDirectory()) {
                // 目录
                this.deleteAllFiles(f);
                f.delete();
            }
        }
    }
}
